package hc.j2me.util;

import hc.core.ContextManager;
import hc.core.IConstant;
import hc.core.IContext;
import hc.core.util.ByteUtil;
import hc.j2me.Starter;
import hc.j2me.item.IPort;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.TimeZone;
import hc.core.util.Stack;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Item;

/**
 * 仅J2ME环境使用，PC模式下仅使用远控，
 * 注意：不可多实例化
 * @author d
 *
 */
public class Jcip {
	public static final Image SYSTEM_IMAGE = loadSysImage();
	
	private static Image loadSysImage(){
		try {
			return Image.createImage("/hc/j2me/res/hc_32.png");
		} catch (IOException e) {
            e.printStackTrace();
		}
		return null;
	}
	
	private static Jcip instance;
	
	public static Jcip getInstance(){
		return instance;
	}
	
	public static void setInstance(Jcip jcip){
		instance = jcip;
	}
	
	public Jcip(String xml) {
		ini(xml);
	}

	private void ini(String xml) {
		index = 0;
		chars = xml.toCharArray();
        charArrLen = chars.length;
		c = chars[index];
	}
	
	public void setIniXML(String xml){
		ini(xml);
	}
	
	private char[] chars;
	
	private static int index, charArrLen;
	private static char c;
	
	public void initForTest(){
		while(c == '<' || c == ' ' || c == '\n' || c == '\r'){
			c = chars[index++];
		}
	}
	
	
	public Object toObject(){
		try {
			String itemClass = "hc.j2me.item." + getString();
			//hc.core.L.V=hc.core.L.O?false:LogManager.log("new Object [" + itemClass + "]");
			return Class.forName(itemClass).newInstance();
		} catch (Exception e) {
			ContextManager.displayMessage(Starter.getUIString(ScreenUtil.ERROR), e.toString(), IContext.ERROR, 0);		
		}
		return null;
	}

	public String[] getArrString(){
		//hc.core.L.V=hc.core.L.O?false:LogManager.log("Enter ArrString");
		final Stack v = new Stack(4);
		while(c != ']'){
			while(c != '\'' && c != ']'){
				c = chars[index++];
			}
			
			//数组内无成员的情形
			if(c == ']'){
				break;
			}
			
			//hc.core.L.V=hc.core.L.O?false:LogManager.log("StringArr : new String");
			Object obj = getString();
			v.push(obj);
			
			//尾部需要检查并退出。
			while(c != ']' && c != '\''){
				c = chars[index++];
			}
		}
		//hc.core.L.V=hc.core.L.O?false:LogManager.log("Exit ArrString");
		if(index == charArrLen){
			
		}else{
			//取下一位
			c = chars[index++];
		}
		
		String[] items = new String[v.size()];
		for (int i = 0; i < items.length; i++) {
			items[i] = (String)v.elementAt(i);
		}
		return items;
	}
	
	public boolean[] convert(String[] data){
		boolean[] out = new boolean[data.length];
		for (int i = 0; i < out.length; i++) {
			out[i] = data[i].equals(IConstant.TRUE);
		}
		return out;
	}

	public Item[] getArrItem(){
		//hc.core.L.V=hc.core.L.O?false:LogManager.log("Enter ArrItem");
		final Stack v = new Stack(4);
		while(c != ']'){
			while(c != '\'' && c != ']'){
				c = chars[index++];
			}
			
			//数组内无成员的情形
			if(c == ']'){
				break;
			}
			
			//hc.core.L.V=hc.core.L.O?false:LogManager.log("ArrItem : new Item");
			Object obj = toObject();
			v.push(obj);
			
			//尾部需要检查并退出。
			while(c != ']' && c != '\''){
				c = chars[index++];
			}
		}
		//hc.core.L.V=hc.core.L.O?false:LogManager.log("Exit ArrItem");
        if(index == charArrLen){
            
        }else{
            //取下一位
            c = chars[index++];
        }
        
		Item[] items = new Item[v.size()];
		for (int i = 0; i < items.length; i++) {
			items[i] = (Item)v.elementAt(i);
		}
		return items;
	}

	public Image[] getArrImage(){
		//hc.core.L.V=hc.core.L.O?false:LogManager.log("Enter ArrImage");
		final Stack v = new Stack(4);
		while(c != ']'){
			while(c != '\'' && c != ']'){
				c = chars[index++];
			}
			
			//数组内无成员的情形
			if(c == ']'){
				break;
			}
			
			//hc.core.L.V=hc.core.L.O?false:LogManager.log("ArrImage : new Image");
			Object obj = getImage();
			v.push(obj);
			
			//尾部需要检查并退出。
			while(c != ']' && c != '\''){
				c = chars[index++];
			}
		}
		if(index == charArrLen){
			
		}else{
			//取下一位
			c = chars[index++];
		}
		
		//hc.core.L.V=hc.core.L.O?false:LogManager.log("Exit ArrImage");
		
		Image[] image = new Image[v.size()];
		for (int i = 0; i < image.length; i++) {
			image[i] = (Image)v.elementAt(i);
		}
		return image;
	}

	public Image getImage(){
		String data = getString();
		if(data.equals("null")){
			return null;
		}else if(data.equals("Sys_Img")){
			return SYSTEM_IMAGE;
		}else{
			Image image = decodeBase64ToImage(data);
			if(image == null){
				return SYSTEM_IMAGE;
			}else{
				return image;
			}
		}
	}
	
	public static Image decodeBase64ToImage(String str) {    
	    byte[] data;
		try {
			data = str.getBytes(IConstant.UTF_8);
		    int len = data.length;    
		    byte[] out = ByteUtil.byteArrayCacher.getFree(len);
		    int outsize = ByteUtil.convertToSize(data, len, out);

		    Image image = Image.createImage(out, 0, outsize);
		    ByteUtil.byteArrayCacher.cycle(out);
		    
		    return image;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}    
		return null;
	}
	

	
	public int getInt(){
		return Integer.parseInt(getString());
	}
	
	public Font getFont(){
		return Font.getFont(getInt(), getInt(), getInt());
	}

	public boolean getBool(){
		String data = getString();
		if(data != null && data.equals(IConstant.TRUE)){
			return true;
		}else{
			return false;
		}
	}

	public TimeZone getTimezone(){
		return TimeZone.getTimeZone(getString());
	}
	
	public String getString(){
		if(index == charArrLen 
					|| c == ']'){//判断是否数组结束
				return null;
		}
		while(c != '\''){
			c = chars[index++];
			//尝试init时，会向后取内容，所以加下检查条件
			if(index == charArrLen 
					|| c == ']'){//判断是否数组结束
				return null;
			}
		}
		
		int start = index;
		
		boolean needchange = false;
        String temp = "";
		
		//走过前面的'
		c = chars[index++];
		
		while(! (c == '\'' && chars[index - 2] != '\\')){
			if(c == '\''){
				needchange = true;
                temp = temp + String.valueOf(chars, start, index-2 - start) + "'";
                start = index;
			}
			c = chars[index++];
		}
		
		int end = index-1;

        if(index == charArrLen){
            
        }else{
    		//走过后面的'
            c = chars[index++];
        }
        
		if(needchange){
			temp = temp + String.valueOf(chars, start, index-2 - start);
		}else{
			temp = String.valueOf(chars, start, end - start);
		}
		//hc.core.L.V=hc.core.L.O?false:LogManager.log("Jcip String item:" + temp);
		return temp;
	}

	public void init(IPort port) {

		char bc = c;
		int bIndex = index;
		
		String str = getString();
		if(str != null){
			if(str.equals("Init")){
				port.appendInPort(this);
		
				bc = c;
				bIndex = index;
				str = getString();
			}
		}
		
		if(str != null){
			if(str.equals("IO")){
				port.setIOMode((short)getInt());
				
				bc = c;
				bIndex = index;
				str = getString();
			}
		}
		
		if(str != null){
			if(str.equals("ID")){
				port.setID(getString());
				return;
			}
		}

		c = bc;
		index = bIndex;
	}
}
